#!/bin/bash

set -eu -o pipefail

helpexit() {
  echo "$0 version action"
  exit 1
}

test -n "${1:-}" -a -n "${2:-}" || helpexit

version=${1//.}
action=$2


GIT_URL="https://notabug.org/Krock/dawn.git"
PATCHER_HOME="$HOME/.local/share/paimon-launcher/dawn"
CACHE_TIME=5 # don't update patcher if it was updated within last 5 minutes
TIMESTAMP_FILE="$PATCHER_HOME.timestamp"
scripts_path=`cd "\`dirname \"$0\"\`"; echo "$PWD"`
patcher_dir="$PATCHER_HOME/$version"

# clone or update patcher dir
if [ ! -d "$PATCHER_HOME/.git" ]; then
  echo "Cloning patcher..."
  mkdir -p "$(basename $PATCHER_HOME)"
  git clone $GIT_URL "$PATCHER_HOME"
  touch "$TIMESTAMP_FILE"
else
  if [ ! -e  "$TIMESTAMP_FILE" -o -n "`find \"$TIMESTAMP_FILE\" -mmin +$CACHE_TIME`" ]; then
    echo "Updating patcher..."
    git -C "$PATCHER_HOME" pull
    touch "$TIMESTAMP_FILE"
  fi
fi


get_sudo_content() {
  echo 'set -eu -o pipefail'
  sed '/# START OF SUDO DANGER ZONE/,/# END OF SUDO DANGER ZONE/!d' "$patcher_dir/patch.sh"
}

# unfortunately pkexec doesn't work with pipes like sudo, so we have no chance to execute script as is
# we cut out the sudo part and executing it to test if superuser rights needed (exit code 42 then)
# if so, we do the same part again with su rights provided by pkexec (or not)
# after that we can start the script itself

case $action in
  check)
    echo "SERVERS_BEGIN"
    sed '/servers=/,/EOF/!d;/EOF/d' "$patcher_dir/patch.sh"
    echo "SERVERS_END"
    # make script exit with code 42 in case it wants sudo
    check_script=`get_sudo_content | sed 's/ sudo / exit 42 # /g'`
    bash -c "$check_script"
    ;;

  block)
    block_script=`get_sudo_content`
    # User already accepted, so reply 'y'
    QUIET=1 "$scripts_path/sudo-wrapper" bash -c "$block_script" <<< 'y'
    ;;

  patch)
    # User already accepted, so reply 'y'
    echo "Starting $patcher_dir/patch.sh"
    bash "$patcher_dir/patch.sh" <<< 'y'
    if [ -f "$patcher_dir/patch_anti_logincrash.sh" ]; then
      # User already accepted, so reply 'y'
      bash "$patcher_dir/patch_anti_logincrash.sh" <<< 'y'
    fi

    echo
    echo "Note: removing 'start' from launcher.bat to make Start/Stop button work properly"
    sed -i 's/^start\s\+\(Gen\)/\1/' launcher.bat
    ;;

  revert)
    bash "$patcher_dir/patch_revert.sh"
    ;;

  *)
    echo "unsupported action $action"
    helpexit
    ;;
esac
